<?php namespace nimo\common\csv;

use nimo\common\validator\BatchValidator;

class SimpleInterceptor implements ExportInterceptor, ImportInterceptor {

	protected $datas = array();
	protected $skipFirst = false;

    public function __construct(BatchValidator $validator = null, CsvConverter $converter = null, array $configs=array()) {
    	$this->validator =$validator;
    	$this->converter =$converter;
        $this->skipFirst = isset($configs['skipFirst']) ? $configs['skipFirst'] : false;
    }

	public function messages() {
		if ($this->validator==null ) {
			return null;
		}
		return $this->validator->getMessageBag()->all();
	}

	public function getDatas() {
		return $this->datas;
	}

	public function setDatas($datas) {
		$this->datas = $datas;
	}

	public function export($exporter) {
		// customized logic to write csv file
		foreach ($this->datas as $data) {
			//write data to csv file
			$exporter->export($data);
		}
	}

	public function import($rowno, $csv_data){
		if ( is_null($rowno)) {
			// end of process
			return;
		}
		if ($rowno===0 && $this->skipFirst) {
			return;
		}
		if ($this->validator!=null && !$this->validator->passesRow($rowno, $csv_data)) {
			return;
		}
		// memorize data from csv file 
		if ($this->converter!=null) {
			$this->datas[$rowno] = $this->converter->convert($csv_data);
		} else {
			$this->datas[$rowno] = $csv_data;			
		}
	}
}
